import _ from 'lodash';

const versionKey = {
  投资版: 'investment',
  战规版: 'strategy',
  集团审批版: 'president',
  调整前: 'before',
};
const types = ['before', 'president', 'investment', 'strategy'];

const setNumber = (num, precision) => {
  let setNum = num || '-';
  if ((num === 0 || num) && num !== '-') {
    setNum = Math.abs(num).toFixed(precision);
  }
  return setNum;
};

export const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

export const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    const x = value;
    if (x.pid === pid) {
      if (hasChildren(list, x)) {
        x.children = [];
        x.children = buildTree(list, x.id);
      }
      tree.push(x);
    }
  });
  return tree;
};

export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

// list1 = 本次调价对整盘核心指标的影响
// list2 = 本次调整预警简报
const textName = {
  before: '调整前',
  president: '集团版',
  check: '年初考核版',
  investment: '投资版',
  strategy: '战规版',
};
export const setBulletinWarnInfo = (list1, list2, contrastType, projectType) => {
  const coreWarnInfoList = _.cloneDeep(list1);
  const bulletinWarnInfo = _.cloneDeep(list2);
  let warnFlag = 0;
  const filterData = _.filter(list1, item => item.type === 'createProfit');
  if (!_.isEmpty(filterData) && !_.isEmpty(bulletinWarnInfo)) {
    const value1 = filterData[0].after; // 调价后
    const value2 = filterData[0][contrastType]; // 年初考核版或者投资版
    // console.log(value1, 'value1');
    // console.log(value2, 'value2');
    if ((value1 || value1 === 0) && (value2 || value2 === 0)) {
      const diffValue = value1 - value2;
      if (projectType === '首开') {
        if (diffValue === 0) {
          bulletinWarnInfo[0].status = 'success';
          bulletinWarnInfo[0].type = `创造利润率与${textName[contrastType]}相比，未折损`;
          bulletinWarnInfo[0].content = `${
            textName[contrastType]
          }整盘创造利润率 ${value2} %,本次调整后整盘创造利润率 ${value1} %, 未折损${diffValue.toFixed(
            2,
          )} %`;
        } else {
          bulletinWarnInfo[0].status = 'warning';
          bulletinWarnInfo[0].type = `创造利润率与${textName[contrastType]}相比，已折损`;
          bulletinWarnInfo[0].content = `${
            textName[contrastType]
          }整盘创造利润率 ${value2} %,本次调整后整盘创造利润率 ${value1} %, 已折损${diffValue.toFixed(
            2,
          )} %`;
        }
      }
      if (projectType !== '首开') {
        if (diffValue <= -3) {
          // 触发预警
          bulletinWarnInfo[0].status = 'warning';
          bulletinWarnInfo[0].type = `创造利润率与${textName[contrastType]}相比，折损超过 3 %`;
          bulletinWarnInfo[0].content = `${
            textName[contrastType]
          }整盘创造利润率 ${value2} %,本次调整后整盘创造利润率 ${value1} %,折损 ${diffValue.toFixed(
            2,
          )} %`;
        } else {
          // 未触发预警
          bulletinWarnInfo[0].status = 'success';
          bulletinWarnInfo[0].type = `创造利润率与${textName[contrastType]}相比，折损未超过 3 %`;
          bulletinWarnInfo[0].content = `${
            textName[contrastType]
          }整盘创造利润率 ${value2} %,本次调整后整盘创造利润率 ${value1} %, ${
            diffValue >= 0 ? '增加' : '折损'
          } ${diffValue.toFixed(2)} %`;
        }
      }
      // if (projectType === '首开') {
      //   if (diffValue === 0) {
      //     // 未触发预警
      //     bulletinWarnInfo[0].status = 'success';
      //     bulletinWarnInfo[0].type = `创造利润率与${textName[contrastType]}相比，未折损`;
      //     bulletinWarnInfo[0].content = `${
      //       textName[contrastType]
      //     }整盘创造利润率 ${value2} %,本次调整后整盘创造利润率 ${value1} %, ${
      //       diffValue >= 0 ? '增加' : '折损'
      //     } ${diffValue.toFixed(2)} %`;
      //   }
      // } else {
      //   // 触发预警
      //   bulletinWarnInfo[0].status = 'warning';
      //   bulletinWarnInfo[0].type = `创造利润率与${textName[contrastType]}相比，已折损`;
      //   bulletinWarnInfo[0].content = `${
      //     textName[contrastType]
      //   }整盘创造利润率 ${value2} %,本次调整后整盘创造利润率 ${value1} %,折损 ${diffValue.toFixed(
      //     2,
      //   )} %`;
      // }
      coreWarnInfoList[0].profit = diffValue;
    } else {
      // 初始化未触发预警
      bulletinWarnInfo[0].status = 'success';
      bulletinWarnInfo[0].type =
        projectType === '首开'
          ? `创造利润率与${textName[contrastType]}相比，未折损`
          : `创造利润率与${textName[contrastType]}相比，折损未超过 3 %`;
      bulletinWarnInfo[0].content = '';
    }
  }
  const warningNum = _.filter(bulletinWarnInfo, x => x.status === 'warning')?.length;
  warnFlag = warningNum > 0 ? 1 : 0;
  return {
    coreWarnInfoList,
    bulletinWarnInfo,
    warnFlag,
  };
};

// 设置核心指标
export const getCoreWarnInfoList = list => {
  let cloneList = _.cloneDeep(list);
  let createProfitMarsVersion = null;
  cloneList = cloneList?.map(item => {
    const itemX = item;

    types.forEach(key => {
      const setValCondition = (item.after && item[key]) || item.after === 0 || item[key] === 0;
      const keyCap = key.toLowerCase().replace(/( |^)[a-z]/g, L => L.toUpperCase());
      // 调整后金额减指标版本
      itemX[`after${keyCap}`] = setValCondition ? item.after - item[key] : null;
    });

    // 获取创造利润率 的对标状态
    if (item.type === 'createProfit') {
      createProfitMarsVersion = item.marsVersion;
    }
    return itemX;
  });

  // 设置利润率变动预警
  if (createProfitMarsVersion === '投资版') cloneList[0].profit = cloneList[3].afterInvestment;
  if (createProfitMarsVersion === '战规版') cloneList[0].profit = cloneList[3].afterStrategy;
  if (createProfitMarsVersion === '集团审批版') cloneList[0].profit = cloneList[3].afterPresident;
  if (createProfitMarsVersion === '调整前') cloneList[0].profit = cloneList[3].afterBefore;

  return cloneList;
};

export const getBulletinWarnInfo = (list, creWarnInfoList) => {
  let warnFlag = 0; // 预警状态 0没有预警 1有预警
  let isWarnList = [];
  const newList = [];
  const cloneCoreWarnInfoList = _.cloneDeep(creWarnInfoList);
  if (!_.isEmpty(list) && !_.isEmpty(cloneCoreWarnInfoList)) {
    newList.unshift(_.head(list));
    // 根据核心指标生成对应预警信息---begin
    cloneCoreWarnInfoList.forEach(item => {
      let keyCap = 'after';
      let status = 'success';
      let type = '无对标版本';
      let content = '-';
      let differenceVal = '-';
      let marsVersionVal = '-';
      let afterVal = '-';
      if (item.type === 'equityPrice' && item.marsVersion) {
        let lossStatus = '未折损';
        // 取对标版本调整前数值
        keyCap += versionKey[item.marsVersion]
          .toLowerCase()
          .replace(/( |^)[a-z]/g, L => L.toUpperCase());

        if (item[versionKey[item.marsVersion]] || item[versionKey[item.marsVersion]] === 0) {
          marsVersionVal = item[versionKey[item.marsVersion]];
        }
        if (item[keyCap] || item[keyCap] === 0) {
          differenceVal = item[keyCap];
        }
        if (item.after || item.after === 0) {
          afterVal = item.after;
        }

        if (differenceVal > 0) {
          status = 'success';
          lossStatus = '未折损';
        } else if (differenceVal < 0) {
          status = 'warning';
          lossStatus = '已折损';
        }

        if ((marsVersionVal === 0 || marsVersionVal) && marsVersionVal !== '-') {
          marsVersionVal = Number(marsVersionVal).toFixed(0);
        }
        if ((differenceVal === 0 || differenceVal) && differenceVal !== '-') {
          differenceVal = Number(differenceVal).toFixed(0);
        }
        if ((afterVal === 0 || afterVal) && afterVal !== '-') {
          afterVal = Number(afterVal).toFixed(0);
        }

        type = `调整后整盘货值与${item.marsVersion}相比，${lossStatus}`;
        content = `项目整盘货值，${item.marsVersion}货值 ${marsVersionVal}万元，本次调整后货值 ${afterVal} 货值差异 ${differenceVal} 万元。`;

        newList.push({
          id: 2,
          status,
          type,
          content,
          contrastType: item.marsVersion,
        });
      }
      if (item.type === 'createProfit' && item.marsVersion) {
        let lossStatus = '未折损';
        let lossStatus1 = '提升';
        // 取对标版本调整前数值
        keyCap += versionKey[item.marsVersion]
          .toLowerCase()
          .replace(/( |^)[a-z]/g, L => L.toUpperCase());
        if (item[versionKey[item.marsVersion]] || item[versionKey[item.marsVersion]] === 0) {
          marsVersionVal = item[versionKey[item.marsVersion]];
        }
        if (item[keyCap] || item[keyCap] === 0) {
          differenceVal = item[keyCap];
        }
        if (item.after || item.after === 0) {
          afterVal = item.after;
        }

        if (differenceVal > 0) {
          status = 'success';
          lossStatus = '未折损';
          lossStatus1 = '提升';
        } else if (differenceVal < 0) {
          status = 'warning';
          lossStatus = '已折损';
          lossStatus1 = '折损';
        }

        if ((marsVersionVal === 0 || marsVersionVal) && marsVersionVal !== '-') {
          marsVersionVal = Number(marsVersionVal).toFixed(2);
        }
        if ((afterVal === 0 || afterVal) && afterVal !== '-') {
          afterVal = Number(afterVal).toFixed(2);
        }
        differenceVal = setNumber(differenceVal, 2);

        type = `调整后创造利润率与${item.marsVersion}相比，${lossStatus}`;
        content = `${item.marsVersion}整盘创造利润率 ${marsVersionVal} %, 本次调整后整盘创造利润率 ${afterVal} %，${lossStatus1} ${differenceVal} %。`;

        newList.push({
          id: 3,
          status,
          type,
          content,
          contrastType: item.marsVersion,
        });
      }
      if (item.type === 'meltingIRR' && item.marsVersion) {
        let lossStatus = '未折损';
        let lossStatus1 = '提升';
        // 取对标版本调整前数值
        keyCap += versionKey[item.marsVersion]
          .toLowerCase()
          .replace(/( |^)[a-z]/g, L => L.toUpperCase());
        if (item[versionKey[item.marsVersion]] || item[versionKey[item.marsVersion]] === 0) {
          marsVersionVal = item[versionKey[item.marsVersion]];
        }
        if (item[keyCap] || item[keyCap] === 0) {
          differenceVal = item[keyCap];
        }
        if (item.after || item.after === 0) {
          afterVal = item.after;
        }

        if (differenceVal > 0) {
          status = 'success';
          lossStatus = '未折损';
          lossStatus1 = '提升';
        } else if (differenceVal < 0) {
          status = 'warning';
          lossStatus = '已折损';
          lossStatus1 = '折损';
        }

        if ((marsVersionVal === 0 || marsVersionVal) && marsVersionVal !== '-') {
          marsVersionVal = Number(marsVersionVal).toFixed(2);
        }
        if ((afterVal === 0 || afterVal) && afterVal !== '-') {
          afterVal = Number(afterVal).toFixed(2);
        }
        differenceVal = setNumber(differenceVal, 2);

        type = `调整后非融IRR与${item.marsVersion}相比，${lossStatus}`;
        content = `${item.marsVersion}非融IRR ${marsVersionVal} %, 本次调整后非融IRR ${afterVal} %，${lossStatus1} ${differenceVal} %。`;

        newList.push({
          id: 4,
          status,
          type,
          content,
          contrastType: item.marsVersion,
        });
      }
      if (item.type === 'meltingInvestment' && item.marsVersion) {
        let lossStatus = '已减少';
        let lossStatus1 = '增加';
        // 取对标版本调整前数值
        keyCap += versionKey[item.marsVersion]
          .toLowerCase()
          .replace(/( |^)[a-z]/g, L => L.toUpperCase());
        if (item[versionKey[item.marsVersion]] || item[versionKey[item.marsVersion]] === 0) {
          marsVersionVal = item[versionKey[item.marsVersion]];
        }
        if (item[keyCap] || item[keyCap] === 0) {
          differenceVal = item[keyCap];
        }
        if (item.after || item.after === 0) {
          afterVal = item.after;
        }

        if (differenceVal > 0) {
          status = 'warning';
          lossStatus = '未减少';
          lossStatus1 = '增加';
        } else if (differenceVal < 0) {
          status = 'success';
          lossStatus = '已减少';
          lossStatus1 = '减少';
        }

        if ((marsVersionVal === 0 || marsVersionVal) && marsVersionVal !== '-') {
          marsVersionVal = Number(marsVersionVal).toFixed(2);
        }
        if ((afterVal === 0 || afterVal) && afterVal !== '-') {
          afterVal = Number(afterVal).toFixed(2);
        }
        differenceVal = setNumber(differenceVal, 2);

        type = `调整后非融静态投资回收期与${item.marsVersion}相比，${lossStatus}`;
        content = `${item.marsVersion}非融静态投资回收期 ${marsVersionVal}， 本次调整后非融静态投资回收期 ${afterVal}，${lossStatus1} ${differenceVal}。`;

        newList.push({
          id: 5,
          status,
          type,
          content,
          contrastType: item.marsVersion,
        });
      }
    });
  }
  // 根据核心指标生成对应预警信息---end
  // 如果存在一条预警则改变预警状态
  isWarnList = _.filter(newList, x => x.status === 'warning');
  if (!_.isEmpty(isWarnList)) warnFlag = 1;
  return {
    warnFlag,
    bulletinWarnInfo: newList,
  };
};
